Skip to content

feat: accept std::string and std::string_view as keys in operator[] - #6316

Merged
henryiii merged 2 commits into
pybind:masterfrom
henryiii:feat/item-accessor-string-key
Dec 1, 2026
Merged

henryiii merged 2 commits into
pybind:masterfrom
henryiii:feat/item-accessor-string-key

Conversation

@henryiii

@henryiii henryiii commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

I prefer #6286. I don't buy the argument that dict keys are special vs. any other conversion; objects that cannot be reconverted or have really expensive conversions are very bad dict keys. If you are doing something weird and making dict keys that can't be reconverted, you should know what you are doing.

But if we are on this one at a time, std::string and std::string_view are probably the most important one after const char *.

🤖 AI text below 🤖

Description

Follow-up to #6291, requested in #6286 (comment).

obj[key] now accepts a std::string or a std::string_view (C++17) as the key, for example d[std::string("s")], d[std::string_view("s")] and o[key][other_key]. The key is built with py::str, so embedded NUL characters are kept.

The change adds one constrained template overload of object_api::operator[]. It matches only std::string and std::string_view, through a new detail::is_string_key trait. A plain const std::string & overload would also take part in overload resolution for types that have an implicit conversion to std::string, and could make calls that compile today ambiguous. The handle, object &&, const char * and integer overloads are unchanged.

Other key types still need an explicit py::str(key) or py::cast(key).

Suggested changelog entry:

  • operator[] on py::object, py::dict and accessors now accepts a std::string or std::string_view as the key.

Assisted-by: ClaudeCode:claude-fable-5-2
@henryiii
henryiii marked this pull request as ready for review November 26, 2026 05:01
Assisted-by: ClaudeCode:claude-opus-5-5
@henryiii henryiii changed the title feat: accept std::string as a key in operator[] feat: accept std::string and std::string_view as keys in operator[] Nov 26, 2026
@rwgk

rwgk commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

— codex on behalf of Ralf —

No actionable code findings. The overload is constrained to exact std::string and, when available, std::string_view types, so implicit conversions do not add candidates for existing keys. It delegates to the existing length-aware string conversion. The regression covers reads, writes, nested access, temporaries, and embedded NULs. I also verified embedded NULs and existing key overloads in C++11 and C++17. Regression test

The abi3t-on-GIL job failed during configure with HTTP 504 downloading Catch2. The targeted rerun passed. Rerun job

@cielavenir

Copy link
Copy Markdown
Contributor

to be clear, no need to merge this if #6286 can be merged by 3.2.0 release.

@rwgk

rwgk commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

to be clear, no need to merge this if #6286 can be merged by 3.2.0 release.

I'm still opposed to merging 6286:

  • it might be easy and seem convenient at first,
  • but I don't think it's wise:

The superficial convenience afforded by 6286 is very minor and at the same time a trap. It makes expensive repeated to-Python conversions much harder to pin-point, certainly for humans, and I believe even for agents (one more mental hoop to jump through).

Requiring py::cast(0) is obviously silly, and that's solved already (#6291).

Requiring py::cast("x") is already not so obviously silly anymore (e.g. bytes vs str; large blobs), but on balance it still seems better to me to not require it (this PR).

Not requiring py::cast (#6286) for arbitrary other objects is a trap for conversions that are expensive. Better make it obvious; in my mind a clear case of "explicit is better than implicit".

@rwgk rwgk left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

codex GPT-6.2-Sol ultra (I pointed it at my previous comment):

No actionable findings at commit 20fb21e. The overload is constrained to std::string and std::string_view, which preserves existing overload resolution. It uses the length-aware py::str conversion and stores the resulting Python key in the accessor, so embedded NULs and temporary views are handled correctly. PR #6316 · Implementation

Your concern about #6286 applies even to valid, hashable keys. A std::pair<std::string, std::string> would rebuild a Python tuple and convert both strings on every lookup. An explicit py::cast(key) before the loop makes that cost visible and lets callers reuse the result. #6316 still converts strings on each use, but confines the new implicit conversion to those two types. Your comment · #6286 conversion path

@henryiii

henryiii commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator Author

I still think the AI is stuck on a non-issue. If you have a tuple of values, building a tuple isn't that costly, you have to rebuild it if any values are not constant, and if the whole thing is constant, why not cache the value you get out instead of caching the key you put in? That's even faster! Lots of other places in pybind11 automatically convert, that's why pybind11 is easy to use. I don't think dict keys are special.

The time saved by having it just work out of the box is likely better than the time wasted when it fails to compile and you have to add py::cast. AI can help you find slow spots in your code if it's an issue. You can still cache the key, after all!

If pybind11 wasn't designed around automatic conversion, or if this is rust, it might be different, but it's not how the rest of the library was designed.

But fine.

@henryiii
henryiii merged commit 1f9c26c into pybind:master Dec 1, 2026
166 of 167 checks passed
@henryiii
henryiii deleted the feat/item-accessor-string-key branch December 1, 2026 02:12
@github-actions github-actions Bot added the needs changelog Possibly needs a changelog entry label Dec 1, 2026
@rwgk

rwgk commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

I agree the std::pair<std::string, std::string> example isn't a great illustration for my "potentially expensive conversions should be obvious" argument. The blobs (binary large objects) I mentioned are more plausible; large sets or vectors similarly.

But this got me to ask another question:

I wonder, is there a plausible case where an automatic C++-to-Python conversion for the same C++ object produces Python objects that can work as dict keys, but don't compare equal?

This is what codex pulled out:

Yes. A callback registry is a plausible case. With pybind11/functional.h, converting the same std::function holding a capturing lambda creates a fresh Python callable each time. The two callables are hashable, return the same result, and compare unequal. I reproduced this with #6286’s proposed overload on CPython 3.15.2. Function caster · Probe results

const std::function<int(int)> callback = [offset = 42](int x) { return x + offset; };
py::dict d;
d[callback] = 1;
py::object value = d[callback];  // KeyError with #6286

A second assignment would create a second entry. Casting once with const py::object key = py::cast(callback); and reusing key makes both operations use the same Python callable.

A copyable py::class_ instance with default identity equality is another ordinary case. For a C++-owned lvalue with no registered Python wrapper, each default cast wraps a separate copy. The two copies can have identical fields and still be distinct keys. A double NaN is the simplest built-in example. Instance lookup and copy · Python NaN comparison

The same issue already exists with dict.get(), dict.contains(), or two separate explicit casts. What makes d[callback] = …; d[callback] surprising is how strongly that spelling suggests reuse of the same key. Existing dict methods


I think such things will be rare, but I've actually stumbled over corner cases like that in real life a few times.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs changelog Possibly needs a changelog entry

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants